package com.mycompany.app.service;


import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service("authenticationService")
public class AuthenticationService implements IAuthenticationService {
	
	protected final Log logger = LogFactory.getLog(getClass());

	@Resource(name = "authenticationManager")
	private AuthenticationManager authenticationManager; // specific for Spring Security


	public boolean login(String username, String password) {
		try {
			logger.info("validate username "+username);
			Authentication authenticate = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(
							username, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(
						authenticate);				
				return true;
			}
		} catch (AuthenticationException e) {			
		}
		return false;
	}


	public void logout() {
		logger.info("Closed session");
		SecurityContextHolder.getContext().setAuthentication(null);
		SecurityContextHolder.clearContext();
		//currentUser.unauthenticate();
	}

	
}
